import { login, logout, getInfo, register, updateUser } from '@/api/user'
import { getToken, setToken, removeToken, isValidJWTToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    userInfo: null,
    isLoggedIn: false
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
    state.isLoggedIn = !!token
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo
  },
  UPDATE_USER_INFO: (state, userInfo) => {
    state.userInfo = { ...state.userInfo, ...userInfo }
  }
}

const getters = {
  isLoggedIn: state => {
    return !!state.token && state.isLoggedIn
  },
  userInfo: state => {
    return state.userInfo || {}
  },
  isStoreOwner: state => {
    return state.userInfo && state.userInfo.sign === 1
  }
}

const actions = {
  // user login
  login({ commit }, userInfo) {
    const { username, password } = userInfo
    return new Promise((resolve, reject) => {
      console.log('发送登录请求:', { username: username.trim(), password: password })
      login({ username: username.trim(), password: password })
        .then(response => {
          console.log('登录响应完整对象:', response)
          console.log('response.data:', response.data)
          console.log('response.data类型:', typeof response.data)
          
          const { data } = response
          console.log('解构后的data:', data)
          console.log('data类型:', typeof data)
          
          // 检查响应结构 - 后端返回格式: {code: 20000, msg: "成功", data: "jwt_token"}
          if (data && data.code === 20000 && data.data) {
            const token = data.data
            console.log('从data.data获取到token:', token)
            console.log('token类型:', typeof token)
            
            // 使用新的JWT token验证函数
            if (isValidJWTToken(token)) {
              console.log('Token验证通过，设置token')
              commit('SET_TOKEN', token)
              setToken(token)
              resolve({ token: token })
            } else {
              console.error('Token格式不正确:', token)
              reject(new Error('登录失败：token格式不正确'))
            }
          } else {
            console.error('响应格式错误:', data)
            console.error('data.code:', data?.code)
            console.error('data.data:', data?.data)
            reject(new Error('登录失败：响应格式错误'))
          }
        })
        .catch(error => {
          console.error('登录请求失败:', error)
          reject(error)
        })
    })
  },

  // user register
  register({ commit }, userInfo) {
    const { username, password, email } = userInfo
    return new Promise((resolve, reject) => {
      register({ 
        username: username.trim(), 
        password: password, 
        email: email.trim() 
      })
        .then(response => {
          resolve(response)
        })
        .catch(error => {
          reject(error)
        })
    })
  },

  // get user info
  getInfo({ commit, state }) {
    return new Promise((resolve, reject) => {
      getInfo(state.token).then(response => {
        const { data } = response

        if (!data || !data.data) {
          return reject('Verification failed, please Login again.')
        }

        const userInfo = data.data
        commit('SET_USER_INFO', userInfo)
        resolve(userInfo)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // update user info
  updateUserInfo({ commit }, userInfo) {
    return new Promise((resolve, reject) => {
      updateUser(userInfo).then(response => {
        commit('UPDATE_USER_INFO', userInfo)
        resolve(response)
      }).catch(error => {
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // must remove token first
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove token first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

